import axios, {AxiosRequestConfig} from "axios";
import {message, notification} from "antd";
import store from "store2";
import _ from "lodash";
import URI from "urijs";
import {IResponse} from "@/common/common";
import LoginStore from "@/common/store/LoginStore";
import config from "@/config/config";
import {clearLocalStorage, getToken, TOKEN} from "@/common/util";

axios.defaults.timeout = 10000;
axios.defaults.validateStatus = () => true;
axios.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";
axios.defaults.headers.get["Content-Type"] = "application/json;charset=utf-8";

export interface RequestConfig extends AxiosRequestConfig {
  token?: string
  useCache?: boolean
  ignoreAuth?: boolean
}

export function checkExpire(config: RequestConfig) {
  if (config.ignoreAuth || !config.url) {
    return false;
  }
  return false;
}

// export function getUserInfo(): IUser | undefined {
//   const userInfo = store.get(storeKey.userInfo);
//   if (userInfo && !_.isEmpty(userInfo)) {
//     return userInfo;
//   }
//   loginStore.logout();
//   return undefined;
// }

export function checkAndSetToken(config: RequestConfig) {
  // const user = getUserInfo();
  // if (!user) {
  //   return false;
  // }
  // header["SAAS-TOKEN"] = user.token;
  return true;
}

export function request(config: RequestConfig) {
  if (!config.headers) {
    config.headers = {};
  }

  const token = getToken()
  if (token) {
    config.headers["Authorization"] = token
  }

  return new Promise<any>((resolve, reject) => {
    axios(config).then(res => {
      if (res.status !== 200) {
        message.error(res.status + ": " + res.statusText)
        resolve({code: res.status, message: res.statusText})
        return
      }

      const code = res.data.code;
      if (code === 0) {
        resolve(res.data);
        return;
      }

      if (code === 401) {
        clearLocalStorage()
      } else if (code === 403) {
        message.warning("您没有操作权限").then(r => r)
      } else {
        message.error(res.data.message).then(r => r)
      }

      resolve(res.data)
    }, (err) => {
      console.log(`[请求失败]：网络错误`, err)
      message.error(err).then(r => r)
      resolve({code: 500, message: err})
    }).catch(err => {
      console.log(`[请求失败]：网络错误`, err)
      message.error(err).then(r => r)
      resolve({code: 500, message: err})
    })
  })
}

export default (config: RequestConfig) => {
  if (checkExpire(config)) {
    return new Promise<any>((resolve, reject) => {
      resolve({} as any);
    });
  }
  if (!config.method || config.method.toUpperCase() === "GET") {
    addUrlQuery(config);
  }
}

export function addUrlQuery(config: RequestConfig) {
  let uri = URI(config.url);
  if (config.params) {
    for (const p of Object.keys(config.params)) {
      if (p && config.params[p] !== undefined) {
        const para: any = {};
        para[p] = config.params[p];
        uri.addQuery(para);
      }
    }
    delete config.params;
  }
  if (!config.useCache && !config.params?.useCache) {
    uri = uri.addQuery({timestamp: Date.now()});
  }
  config.url = uri.readable();
}

const api = config.api
const baseURL = api.baseURL
const wls = window.localStorage

export function cyGet(note = '', url = '', params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: url,
      method: 'get',
      params: params,
    }).then(res => {
      if (res.data.code !== 0) {
        console.log(`  [请求${note}成功] error:`, res.data.message)
        reject(res.data.message)
        return;
      }
      resolve(res.data.data)
    }).catch(err => {
      console.log(`  [请求${note}失败]：网络错误`, err)
      reject(err)
    })
  })
}

/**
 * @description 将创建日期转化为显示距离最新时间差的方法
 * @date {string} 可被 JS Date() 对象转化的格式化字符串
 * @return {string} 时间差描述
 */
export function cyDateGap(date: string) {
  const A = new Date(date)
  const B = new Date()
  const second = Math.abs(A.getSeconds() - B.getSeconds()) / 1000
  const minute = second / 60
  const hour = minute / 60
  if (second < 60)
    return `${Math.floor(second)}秒前`
  if (minute < 60)
    return `${Math.floor(minute)}分钟前`
  if (hour > 24)
    return `${A.getFullYear()}-${A.getMonth() + 1}-${A.getDate()}`
  return `${Math.floor(hour)}小时前`
}
